package com.yellowcong.realm;

import java.util.HashSet;
import java.util.Set;


import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import org.apache.shiro.authc.AuthenticationToken;

import com.yellowcong.model.User;
import com.yellowcong.service.UserService;
import com.yellowcong.token.JwtToken;
import com.yellowcong.utils.JwtUtils;

/**
 * 创建日期:2017年9月23日 <br/>
 * 创建用户:yellowcong <br/>
 * 功能描述:用于授权操作
 */
public class JwtRealm extends AuthorizingRealm {
	
	@Autowired
    private UserService userService;
	
	/**
	 * 判断token是否事我们的这个jwttoekn
	 */
    @Override
	public boolean supports(AuthenticationToken token) {
    	return token instanceof JwtToken;
	}

	/**
     * 用户授权 
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection paramPrincipalCollection) {
    	
    	//获取jwt的用户名和密码信息
    	String username = JwtUtils.getUsername(paramPrincipalCollection.toString());
    	System.out.println(username);
    	
        SimpleAuthorizationInfo info =  new SimpleAuthorizationInfo();
        // 根据用户ID查询角色（role），放入到Authorization里。
        Set<String> roles = new HashSet<String>(); // 添加用户角色
        roles.add("administrator");
        info.setRoles(roles);
        // 根据用户ID查询权限（permission），放入到Authorization里。
        Set<String> permissions = new HashSet<String>(); // 添加权限
        permissions.add("/role/**");
        info.setStringPermissions(permissions);
        return info;
    }

    /**
     * 认证，用户登录
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken  paramAuthenticationToken) throws AuthenticationException {
       
    	JwtToken jwtToken = (JwtToken) paramAuthenticationToken;

    	String token = jwtToken.getToken();
    	//获取token 信息
    	String username = JwtUtils.getUsername(token);
    	if(username == null || "".equals(username.trim())) {
    		 throw new AuthenticationException("用户名为空");
    	}
    	//判断用户 是否存在的情况
    	User user = this.userService.getUserByName(username);
    	if(user == null) {
	   		 throw new AuthenticationException("用户不存在");
	   	}
    	
    	//user信息
        return new SimpleAuthenticationInfo(token, token, getName());
    }

}
